source('codes/00_import_libraries.R')

options(warn=-1)

xvar = 'War'


#------------------------------------------------------------------------
# Functions
#------------------------------------------------------------------------

ols_res = function(dt, xvar, yvar, h, yr_range) {
  # this function takes in the xvar and year and fit ols to all returns

  mod_list = lapply(paste0(yvar, h),
                    fn_fit_ols,
                    xvar = xvar,
                    df   = dt %>% filter(year %in% yr_range)
  )
  
  # compute newey west se
  mod_robust = mapply(
    function(mod, h){coeftest(mod, vcov.=NeweyWest(mod, lag=h, prewhite=FALSE))},
    mod_list,
    h,
    SIMPLIFY = FALSE
  )
  
  # return the adjusted r2
  is_r2 = lapply(mod_list, function(mod) glance(mod)$adj.r.squared * 100) %>%
    unlist()
  
  # create huxtale from regression
  out = huxreg(
    mod_robust,
    coefs        = xvar,
    error_format = "({statistic})",
    stars        = c(`***` = 0.01, `**` = 0.05, `*` = 0.1),
    statistics   = c(0),
    borders      = 0,
    outer_borders= 0,
    note         = NULL
  )
  
  # add the r2 to the huxtable
  out = c(out$model1[-1], is_r2)
  
  return(out)
}



fn_res = function(country, yr_list, panel_name) {
  
  df = readRDS('input/combined_monthly_stock_returns.rds')[[country]]
  dt = readRDS('input/combined_data.rds')[['base']] %>%
    select(ym, any_of(xvar)) %>% 
    inner_join(df, by = 'ym') %>% 
    mutate(
      year = year(ym),
      across(starts_with('mkt'), ~ .*12),
    ) %>% 
    drop_na(mkt1) %>% 
    select(ym, year, starts_with('mkt'), any_of(xvar))
  
  
  row_names = sapply(yr_list, function(yr_range) glue('{min(yr_range)}:{max(yr_range)}'))
  
  lapply(yr_list, function(yr_range) {
    ols_res(dt = dt, xvar = xvar, yvar = 'mkt', h = 1, yr_range = yr_range)
  }) %>%
    do.call(what = rbind) %>% 
    as_hux() %>% 
    set_align('.') %>% 
    insert_column(row_names) %>%
    set_number_format(2) %>% 
    set_number_format(everywhere, 1, 0) %>% 
    insert_row(panel_name, fill = '') %>% 
    merge_cells(1, everywhere) %>% 
    set_align(1, everywhere, 'center') %>% 
    set_tb_borders(1, everywhere, 0.8) %>% 
    set_bottom_border(final(1), everywhere, 0.8)
}



#------------------------------------------------------------------------
# Results
#------------------------------------------------------------------------

uk = fn_res(
  country = 'uk',
  yr_list = list(1871:2019, 1950:2019, 2000:2019),
  panel_name = 'Panel A: UK FTSE Index' 
)

msci = fn_res(
  country = 'msci',
  yr_list = list(1969:2019, 2000:2019),
  panel_name = 'Panel B: MSCI World Index' 
)

dj = fn_res(
  country = 'dj_ex_us',
  yr_list = list(1992:2019, 2000:2019),
  panel_name = 'Panel C: Dow Jones World Index (Excluding US)' 
)

fta = fn_res(
  country = 'fta',
  yr_list = list(1919:2019, 1950:2019, 2000:2019),
  panel_name = 'Panel D: FTA World Index (Excluding US)' 
)

output = rbind(uk, msci, dj, fta) %>% 
  as_hux() %>% 
  insert_row(c('', '$\\beta$', '$t$-stat', '$R^2$')) %>% 
  set_tb_borders(1, everywhere, 0.8) %>%
  set_align(everywhere, -1, '.') %>% 
  # set_align(1, everywhere, 'center') %>% 
  set_lr_padding(4) %>% 
  set_tb_padding(0) %>% 
  set_escape_contents(FALSE)



#------------------------------------------------------------------------
# Export
#------------------------------------------------------------------------

quick_xlsx(output, file = glue('output/tables/Table_7.xlsx'))
# cat(to_latex(output, tabular_only = TRUE), file = glue('output/tables/Table_7.tex'))
